<?php
/**
 * Journal Model class file 
 *
 * @package Jurnalport
 */

/**
 * Journal Model
 * 
 * @uses Apricot_Model
 * @package Jurnalport
 * @author Jansen Price <jansen.price@gmail.com>
 * @version $Id$
 */
class JournalModel extends Apricot_Model
{
    /**
     * Storage of data path
     * 
     * @var string
     */
    protected $_dataPath = '';

    /**
     * Storage of file
     * 
     * @var string
     */
    protected $_file = 'journal.txt';

    /**
     * Initialize this model
     * 
     * @return void
     */
    public function init()
    {
        $this->_dataPath = realpath('../data') . '/';
        $this->_file     = $this->_dataPath . $this->_file;

        $this->_initDatabase();
    }

    /**
     * Save a new message
     * 
     * @param mixed $message Entry message
     * @param int $date Date timestamp
     * @return bool
     */
    public function save($message, $date = null)
    {
        if (null === $date) {
            $date = time();
        } else {
            if (!is_numeric($date)) {
                $date = strtotime($date);
            }
        }

        $data = array(
            'user'       => 'Jansen',
            'entry_date' => $date,
            'entry_text' => $message,
            'sync'       => 0,
        );

        if ($this->_db->insert('entries', $data)) {
            return true;
        }

        return false;
    }

    /**
     * Retrieve entries
     * 
     * @param int $limit Limit of entries to retrieve
     * @return string
     */
    public function retrieve($limit = 0)
    {
        $sql = "select * from entries order by entry_date desc";

        $limit = (int) $limit;

        if ($limit != 0) {
            $sql .= " limit $limit";
        }

        return $this->getRows($sql);
    }

    /**
     * Initialize database
     * 
     * @return void
     */
    protected function _initDatabase()
    {
        $file = $this->_cfg->dbfile;

        $createSchema = false;
        if (!file_exists($file) || filesize($file) === 0) {
            // If this is a first time, set a flag to create the tables
            $createSchema = true;
        }

        if ($createSchema) {
            // First time db setup
            $this->_createSchema();
            chmod($file, 0666);
        }
    }

    /**
     * Create schema
     * 
     * @return mixed
     */
    protected function _createSchema()
    {
        $sql = "create table entries "
            . "(id INTEGER PRIMARY KEY,"
            . "user varchar(16),"
            . "entry_date INTEGER,"
            . "entry_text TEXT,"
            . "sync INTEGER"
            . ");";

        return $this->_db->safeQuery($sql);
    }
}
